package com.dongdong.android.tangramdemo.home;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.BitmapTypeRequest;
import com.bumptech.glide.Glide;
import com.dongdong.android.tangramdemo.R;
import com.dongdong.android.tangramdemo.utils.CircleTransform;
import com.dongdong.android.tangramdemo.utils.GlideVVSimpleTarget;
import com.dongdong.android.tangramdemo.utils.Httputil;
import com.dongdong.android.tangramdemo.utils.JSONutils;
import com.dongdong.android.tangramdemo.utils.PreviewData;
import com.tmall.wireless.tangram.TangramBuilder;
import com.tmall.wireless.tangram.TangramEngine;
import com.tmall.wireless.tangram.dataparser.concrete.Card;
import com.tmall.wireless.tangram.dataparser.concrete.Cell;
import com.tmall.wireless.tangram.structure.BaseCell;
import com.tmall.wireless.tangram.support.ExposureSupport;
import com.tmall.wireless.tangram.support.SimpleClickSupport;
import com.tmall.wireless.tangram.support.async.CardLoadSupport;
import com.tmall.wireless.vaf.framework.VafContext;
import com.tmall.wireless.vaf.virtualview.event.EventData;
import com.tmall.wireless.vaf.virtualview.event.EventManager;
import com.tmall.wireless.vaf.virtualview.event.IEventProcessor;
import com.tmall.wireless.vaf.virtualview.view.image.ImageBase;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.Map;

import static com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.*;

/**
 * Created by dongdongzheng on 2018/12/3.
 */

public class HomeActivity extends Activity implements View.OnClickListener {

    private static final int HANDLER_UPUI = 1001;

    Context context;
    TextView tvRefresh;
    RecyclerView mRecyContext;
    private TangramEngine engine;
    private TangramBuilder.InnerBuilder builder;

    private Handler mainHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        context = this;
        tvRefresh = (TextView) findViewById(R.id.tv_title_bar_right);
        mRecyContext = (RecyclerView) findViewById(R.id.recy_home_context);

        tvRefresh.setText("刷新");
        tvRefresh.setOnClickListener(this);
        initTangram();
        initVirtual();

        mainHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLER_UPUI:
                        String name = msg.getData().getString("name");
                        PreviewData data = (PreviewData) msg.getData().get("data");
                        for (int i = 0; i < data.templates.size(); i++) {
                            String vvname = name + i;
                            builder.registerVirtualView(vvname);
                            engine.setVirtualViewTemplate(JSONutils.getBase64(data.templates.get(i)));
                        }
                        com.google.gson.JsonArray jsonArray = data.data.getAsJsonArray("jsondata");
                        String json = jsonArray.toString();
                        JSONArray jsdata = null;
                        try {
                            jsdata = new JSONArray(json);
                            engine.setData(jsdata);
                            engine.refresh();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }


                return false;
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        getData("KaBaoHome");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        engine.destroy();
    }

    private void initTangram() {
        builder = TangramBuilder.newInnerBuilder(context);
        engine = builder.build();
        engine.register(SimpleClickSupport.class, new SimpleClickSupport() {
            @Override
            public void setOptimizedMode(boolean optimizedMode) {
                super.setOptimizedMode(optimizedMode);
            }

            @Override
            public void onClick(View targetView, BaseCell cell, int eventType) {
                super.onClick(targetView, cell, eventType);
            }

            @Override
            public void onClick(View targetView, Cell cell, int eventType) {
                super.onClick(targetView, cell, eventType);
            }

            @Override
            public void onClick(View targetView, BaseCell cell, int eventType, Map<String, Object> params) {
                super.onClick(targetView, cell, eventType, params);
            }

            @Override
            public void defaultClick(View targetView, BaseCell cell, int eventType) {
                super.defaultClick(targetView, cell, eventType);
            }
        });

        engine.register(CardLoadSupport.class, new CardLoadSupport());
        engine.register(ExposureSupport.class, new ExposureSupport() {
            @Override
            public void onExposure(@NonNull Card card, int offset, int position) {

            }
        });

        engine.bindView(mRecyContext);

        mRecyContext.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                engine.onScrolled();
            }
        });
    }

    private void initVirtual() {
        VafContext vafContext = engine.getService(VafContext.class);
        vafContext.setImageLoaderAdapter(new IImageLoaderAdapter() {
            @Override
            public void bindImage(String uri, final ImageBase imageBase, int reqWidth, int reqHeight) {
                GlideVVSimpleTarget target = new GlideVVSimpleTarget(imageBase);
                target.setSize(reqWidth, reqHeight);
                BitmapTypeRequest bitmapTypeRequest = Glide.with(getApplicationContext())
                        .load(uri).asBitmap();
                if (imageBase.getTag() != null) {
                    bitmapTypeRequest.transform(new CircleTransform(context)).into(target);
                } else {
                    bitmapTypeRequest.into(target);
                }
            }

            @Override
            public void getBitmap(String uri, int reqWidth, int reqHeight, final Listener lis) {
                GlideVVSimpleTarget target = new GlideVVSimpleTarget(lis);
                target.setSize(reqWidth, reqHeight);
                Glide.with(getApplicationContext())
                        .load(uri).asBitmap().into(target);
            }
        });

        vafContext.getEventManager().register(EventManager.TYPE_Click, new IEventProcessor() {

            @Override
            public boolean process(EventData data) {
                String action = data.mVB.getAction();


                Toast.makeText(HomeActivity.this,
                        "TYPE_Click view name:" + data.mVB.getTag("name")
                                + "\n action:" + action, Toast
                                .LENGTH_LONG).show();
                return true;
            }
        });
        vafContext.getEventManager().register(EventManager.TYPE_Exposure, new IEventProcessor() {

            @Override
            public boolean process(EventData data) {
                //handle here
                return true;
            }
        });
        vafContext.getEventManager().register(EventManager.TYPE_LongCLick, new IEventProcessor() {
            @Override
            public boolean process(EventData data) {

                return true;
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_title_bar_right:
                getData("KouBeiHome");
                break;
            default:
                break;
        }
    }


    private void getData(final String name) {

//        String url = "http://192.168.11.131:7788/" + name + "/data.json";
        String url = "http://192.168.19.30:7788/" + name + "/data.json";
        Log.i("请求url为：", url);

        Httputil.getdata(url, new Httputil.VVout() {
            @Override
            public void out(PreviewData data) {
                if (data != null) {
                    Message msg = mainHandler.obtainMessage();
                    msg.what = HANDLER_UPUI;
                    Bundle b = new Bundle();
                    b.putString("name", name);
                    b.putSerializable("data", data);
                    msg.setData(b);
                    mainHandler.sendMessage(msg);
                }
            }
        });

    }
}
